package cn.sc.jedis;

import cn.sc.jedis.config.CommJedisPoolConfig;
import cn.sc.jedis.config.RedisInfo;
import cn.sc.jedis.serialization.DefaultSerialization;
import cn.sc.jedis.serialization.Serialization;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;

/**
 * @ClassName RedisSingleFactory
 * @Author 谢卓才
 * @Description 创建单机的redis操作类
 * @Date 2022/11/13 9:17
 */
public class RedisSingleFactory implements JedisFactory {

    private Serialization serialization;

    private static JedisPool jedisPool;

    public RedisSingleFactory(){
        this(new DefaultSerialization());
    }

    public RedisSingleFactory(Serialization serialization){
        this.serialization = serialization;
    }


    /**
     * 创建JedisPool类
     * @return
     */
    @Override
    public RedisSingle create(RedisInfo redisInfo) {
        try {
            RedisSingle createRedis = null;
            if (StringUtils.hasLength(redisInfo.getHost())){
                if(jedisPool == null){
                    synchronized (RedisSingleFactory.class){
                        if(jedisPool == null){
                            if(StringUtils.hasLength(redisInfo.getPassword())){
                                //创建一个数据库连接池对象（单例），需要指定服务的ip和端口号,timeout 客户端超时时间单位是毫秒 默认是2000
                                jedisPool = new JedisPool(CommJedisPoolConfig.config(),redisInfo.getHost(), redisInfo.getPort(),3000,redisInfo.getPassword());
                            } else {
                                jedisPool = new JedisPool(redisInfo.getHost(), redisInfo.getPort());
                            }
                        }
                    }
                }
                createRedis = new RedisSingle(jedisPool, serialization);
            }
            return createRedis;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
